package com.corpgovernment.organization.service.impl;

import com.corpgovernment.api.organization.bo.SearchEmployeeInfoRequestBO;
import com.corpgovernment.api.organization.model.expressaddress.*;
import com.corpgovernment.api.organization.model.user.employee.OrgEmployeeVo;
import com.corpgovernment.common.base.BaseRequestVO.UserInfo;
import com.corpgovernment.common.utils.BaseUtils;
import com.corpgovernment.organization.dataloader.db.MbExpressAddressLoader;
import com.corpgovernment.organization.dto.QueryExpressAddressDTO;
import com.corpgovernment.organization.entity.db.MbExpressAddress;
import com.corpgovernment.organization.entity.db.MbOrgInfo;
import com.corpgovernment.organization.enumm.OrgTypeEnum;
import com.corpgovernment.organization.service.IOrganizationEmployeeService;
import com.corpgovernment.organization.service.IOrganizationInfoService;
import com.corpgovernment.organization.service.OrganizationBaseService;
import com.corpgovernment.organization.util.OrganizationUtil;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.ctrip.corp.obt.shard.context.PageContext;
import com.ctrip.corp.obt.shard.sql.mybatis.interceptor.pagination.IPage;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ExpressAddressListServiceImpl extends OrganizationBaseService {

	@Autowired
	private QueryExpressAddressService queryExpressAddressService;
	@Autowired
	private IOrganizationInfoService organizationInfoService;
	@Autowired
	private IOrganizationEmployeeService organizationEmployeeService;
	@Autowired
	private MbExpressAddressLoader expressAddressLoader;

	/**
	 * 获取配送地址
	 * <p>
	 * 获取配送地址
	 */
//    public JSONResult<DeliveryListResponse> expressAddressList(DeliveryListRequest request) {
//        if (StringUtils.isBlank(request.getUid())){
//            log.warn("uid为空");
//            return JSONResult.errorMsg("用户id为空");
//        }
//        DeliveryListResponse returnRes = new DeliveryListResponse();
//        returnRes.setOrgDeliveryList(getOrgDeliveryList(request.getUid(), request.getOrgId()));
//        String uid = request.getUid();
//        String selectVal = request.getSelectVal();
//        Integer pageNum = request.getPageNum();
//        Integer pageSize = request.getPageSize();
//        List<MbExpressAddress> expressAddresses = expressAddressService.listByUid(uid, selectVal, pageNum, pageSize);
//        //区分前后端
//        String source = request.getDevice();
//        if (CollectionUtils.isEmpty(expressAddresses)) {
//            if (DeviceEnum.PC.toString().equalsIgnoreCase(source)) {
//                returnRes.setPcList(Collections.EMPTY_LIST);
//                returnRes.setTotalCount(0);
//            } else {
//                returnRes.setDeliveryList(Collections.EMPTY_LIST);
//            }
//            returnRes.setPageNo(request.getPageNum());
//            returnRes.setPageSize(request.getPageSize());
//            returnRes.setTotalPage(0);
//            return new JSONResult<>(returnRes);
//        }
//        PageInfo pageInfo = new PageInfo(expressAddresses);
//
//        if (DeviceEnum.PC.toString().equalsIgnoreCase(source)) {
//            List<PCUserAddressVo> list = Lists.newArrayList();
//            for (MbExpressAddress expressAddress : expressAddresses) {
//                list.add(convertPCUserAddress(expressAddress));
//            }
//            returnRes.setPcList(list);
//            returnRes.setTotalCount(pageInfo.getTotal());
//        } else {
//            List<DeliveryVo> returnList = new ArrayList<>();
//            if (CollectionUtils.isNotEmpty(expressAddresses)) {
//                for (MbExpressAddress expressAddress : expressAddresses) {
//                    DeliveryVo deliveryListResponse = convertDelivery(expressAddress);
////                    deliveryListResponse.setCountryCode("86");
//                    returnList.add(deliveryListResponse);
//                }
//            }
//            returnRes.setDeliveryList(returnList);
//        }
//        returnRes.setPageNo(pageInfo.getPageNum());
//        returnRes.setPageSize(pageInfo.getPageSize());
//        returnRes.setTotalPage(pageInfo.getPages());
//        return new JSONResult<>(returnRes);
//    }

	/**
	 * 获取配送地址
	 */
    public SearchExpressAddressResponseVO queryExpressAddressList(SearchExpressAddressPageRequestVO request) {

        try {
            initElkLog();
            addElkInfoLog("进入配送地址查询流程");

            // 构建查询参数
            QueryExpressAddressDTO queryParam = buildQueryParam(request);
            addElkInfoLog("查询配送地址参数：%s", JsonUtils.toJsonString(queryParam));

            // 查询配送地址
            IPage<Object> page = PageContext.startPage(request.getPageNum(), request.getPageSize());
            List<MbExpressAddress> expressAddressList = expressAddressLoader.queryByRecord(queryParam);

            if (CollectionUtils.isEmpty(expressAddressList)) {
                addElkInfoLog("未查到可用的配送地址");
                return SearchExpressAddressResponseVO.empty();
            }
            // 构建响应
            return buildExpressAddressListResponse(page, expressAddressList);
        } finally {
			log.info("ExpressAddressListService.queryExpressAddressList获取配送地址{} request：{}{}{}{}", System.lineSeparator(), JsonUtils.toJsonString(request), System.lineSeparator(), System.lineSeparator(), this.getElkInfoLog());
			clearElkLog();
		}
	}

    /**
     * 构建查询配送地址响应
     */
    private SearchExpressAddressResponseVO buildExpressAddressListResponse(IPage<Object> page, List<MbExpressAddress> expressAddressList) {
        SearchExpressAddressResponseVO responseVO = new SearchExpressAddressResponseVO();

        List<PCUserAddressVo> pcList = expressAddressList.stream().map(bean -> {
            PCUserAddressVo pcUserAddressVo = new PCUserAddressVo();
            pcUserAddressVo.setIsCorporation(bean.getIsCorporation());
            pcUserAddressVo.setDefaultAddress(bean.getIsDefault());
            BeanUtils.copyProperties(bean, pcUserAddressVo);
            return pcUserAddressVo;
        }).collect(Collectors.toList());

        responseVO.setPcList(pcList);
        responseVO.setTotalCount(page.getTotal());
        responseVO.setPageNum((int) page.getCurrent());
        responseVO.setPageSize((int) page.getSize());
        responseVO.setTotalPage((int) page.getPages());
        return responseVO;
    }

    /**
     * 构建查询配送地址参数
     */
    private QueryExpressAddressDTO buildQueryParam(SearchExpressAddressPageRequestVO request) {
        UserInfo userInfo = request.getUserInfo();
        QueryExpressAddressDTO queryParam = new QueryExpressAddressDTO();
        queryParam.setSelectValue(request.getSelectVal());
        if (request.getType() == 1) {
            // 查询企业地址(当前组织+父组织配置的地址)
            queryParam.setOrgIds(OrganizationUtil.getParentOrgIdsAndCurrent(organizationInfoService.listAll(), userInfo.getOrgId()));
            queryParam.setIsCorporation(0);
        } else {
            // 查询个人地址
            queryParam.setUid(userInfo.getUid());
            queryParam.setOrgIds(Lists.newArrayList(userInfo.getOrgId()));
            queryParam.setIsCorporation(1);
        }
        return queryParam;
    }

    public String getOrgId(String orgId) {
		//获取一个组织的信息
		MbOrgInfo orgInfo = organizationInfoService.findByOrgId(orgId);
		if (orgInfo != null) {
			//如果是部门，获取该部门公司模板
			if (StringUtils.equals(OrgTypeEnum.D.getCode(), orgInfo.getOrgType(), false)) {
				orgId = orgInfo.getOrgId();
			}
		}
		return orgId;
	}

    /**
     * 地址转换
     */
    public MbExpressAddress convertAddExpressAddress(UserAddressVo userAddressVo) {
        MbExpressAddress expressAddress = new MbExpressAddress();
        expressAddress.setId(userAddressVo.getId());
        expressAddress.setRecipientName(userAddressVo.getRecipientName());
        expressAddress.setRecipientPhone(userAddressVo.getRecipientMobilePhone());
        expressAddress.setProvinceName(userAddressVo.getProvinceName());
        expressAddress.setCityName(userAddressVo.getCityName());
        expressAddress.setDistrictName(userAddressVo.getDistrictName());
        expressAddress.setAddress(userAddressVo.getAddress());
        expressAddress.setPostCode(userAddressVo.getPostCode());
        expressAddress.setProvince(userAddressVo.getProvince());
        expressAddress.setCity(userAddressVo.getCity());
        expressAddress.setDistrict(userAddressVo.getDistrict());
        expressAddress.setUid(userAddressVo.getUid());
        expressAddress.setOrgId(userAddressVo.getOrgId());
        expressAddress.setIsDefault(userAddressVo.isDefaultAddress());
        expressAddress.setCountryCode(userAddressVo.getCountryCode());
        expressAddress.setAddress(userAddressVo.getAddress());
        expressAddress.setIsCorporation(true);
        return expressAddress;
    }


    /**
     * 地址转换
     */
    public MbExpressAddress convertUpdateExpressAddress(UserAddressVo userAddressVo) {
        MbExpressAddress expressAddress = new MbExpressAddress();
        expressAddress.setId(userAddressVo.getId());
        expressAddress.setRecipientName(userAddressVo.getRecipientName());
        expressAddress.setRecipientPhone(userAddressVo.getRecipientMobilePhone());
        expressAddress.setProvinceName(userAddressVo.getProvinceName());
        expressAddress.setCityName(userAddressVo.getCityName());
        expressAddress.setDistrictName(userAddressVo.getDistrictName());
        expressAddress.setAddress(userAddressVo.getAddress());
        expressAddress.setPostCode(userAddressVo.getPostCode());
        expressAddress.setProvince(userAddressVo.getProvince());
        expressAddress.setCity(userAddressVo.getCity());
        expressAddress.setDistrict(userAddressVo.getDistrict());
        expressAddress.setUid(userAddressVo.getUid());
        expressAddress.setOrgId(userAddressVo.getOrgId());
        expressAddress.setIsDefault(userAddressVo.isDefaultAddress());
        expressAddress.setCountryCode(userAddressVo.getCountryCode());
        expressAddress.setAddress(userAddressVo.getAddress());
        return expressAddress;
    }

    /**
     * 地址转换
     */
    private PCUserAddressVo convertPCUserAddress(MbExpressAddress expressAddress) {
        PCUserAddressVo pcUserAddressVo = new PCUserAddressVo();
        pcUserAddressVo.setId(expressAddress.getId());
        pcUserAddressVo.setRecipientName(expressAddress.getRecipientName());
        pcUserAddressVo.setRecipientPhone(expressAddress.getRecipientPhone());
        pcUserAddressVo.setProvinceName(expressAddress.getProvinceName());
        pcUserAddressVo.setCityName(expressAddress.getCityName());
        pcUserAddressVo.setDistrictName(expressAddress.getDistrictName());
        pcUserAddressVo.setAddress(expressAddress.getAddress());
        pcUserAddressVo.setPostCode(expressAddress.getPostCode());
        pcUserAddressVo.setProvince(expressAddress.getProvince());
        pcUserAddressVo.setCity(expressAddress.getCity());
        pcUserAddressVo.setDistrict(expressAddress.getDistrict());
        pcUserAddressVo.setDefaultAddress(expressAddress.getIsDefault());
        return pcUserAddressVo;
    }

    /**
     * 地址转换
     */
    private DeliveryVo convertDelivery(MbExpressAddress expressAddress) {
        DeliveryVo deliveryVo = new DeliveryVo();
        deliveryVo.setId(expressAddress.getId());
        deliveryVo.setRecipientName(expressAddress.getRecipientName());
        deliveryVo.setRecipientMobilePhone(expressAddress.getRecipientPhone());
        deliveryVo.setProvinceName(expressAddress.getProvinceName());
        deliveryVo.setCityName(expressAddress.getCityName());
        deliveryVo.setDistrictName(expressAddress.getDistrictName());
        deliveryVo.setAddress(expressAddress.getAddress());
        deliveryVo.setPostCode(expressAddress.getPostCode());
        deliveryVo.setProvince(expressAddress.getProvince());
        deliveryVo.setCity(expressAddress.getCity());
        deliveryVo.setDistrict(expressAddress.getDistrict());
        deliveryVo.setCountryCode(expressAddress.getCountryCode());
        return deliveryVo;
    }

    /**
     * 预订配送地址取值该预订人的部门里维护的默认地址。如果部门未维护则直接取值该公司地址。不向上寻址。
     */
    private List<DeliveryVo> getOrgDeliveryList(String uid, String orgId) {
		List<DeliveryVo> result = Lists.newArrayList();
		if (StringUtils.isBlank(orgId)) {
			log.warn("orgId为空，uid: " + uid);
			return result;
		}
		List<MbExpressAddress> orgAddresses = queryExpressAddressService.getOrgAddresses(uid, orgId);
		log.info("orgAddress:" + JsonUtils.toJsonString(orgAddresses));
		if (!BaseUtils.isNotNull(orgAddresses)) {
			log.warn("公司地址为空");
			return result;
		}
		//拿公司配送地址的时候，收件人默认为预订人
		OrgEmployeeVo employeeVo = organizationEmployeeService.searchEmployeeInfo(SearchEmployeeInfoRequestBO.create(uid, orgId));
		orgAddresses.forEach(orgAddress -> {
			DeliveryVo deliveryListResponse = convertDelivery(orgAddress);
			if (employeeVo != null) {
				deliveryListResponse.setRecipientName(employeeVo.getName());
				deliveryListResponse.setRecipientMobilePhone(employeeVo.getMobilePhone());
			}
			result.add(deliveryListResponse);
		});
		return result;
	}

    /**
     * 预订配送地址取值该预订人的部门里维护的默认地址。如果部门未维护则直接取值该公司地址。不向上寻址。
     */
    private List<DeliveryVo> getDeliveryList(String orgId, String selectVal) {
        List<DeliveryVo> result = Lists.newArrayList();
        List<MbExpressAddress> orgAddresses = queryExpressAddressService.getAddresses(orgId);
        if (!BaseUtils.isNotNull(orgAddresses)) {
            log.info("公司地址为空");
            return result;
        }
        orgAddresses.forEach(o -> {
            if (StringUtils.isBlank(selectVal) || (StringUtils.isNotBlank(o.getAddress()) && o.getAddress().contains(selectVal))
                    || (StringUtils.isNotBlank(o.getRecipientName()) && o.getRecipientName().contains(selectVal))) {
                DeliveryVo data = JsonUtils.convert(o, DeliveryVo.class);
                data.setCountryCode("86");
                result.add(data);
            }
        });
        return result;
    }
}